<template>
  <div class="login-page">
    <van-nav-bar title="面经"/>
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        label="账号"
        placeholder="用户名"
        :rules="userRules"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^\S{6,20}$/, message: '请输入6~20位的密码'}
        ]"
      />
      <div style="margin: 16px;">
        <van-button  block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>

    <router-link class="link" to="/register">还没有账号，去注册</router-link>
  </div>
</template>

<script>
import { loginAPI } from '../api/user'
export default {
  name: 'login-page',
  data () {
    return {
      username: '',
      password: '',
      userRules: [
        { required: true, message: '请填写密码' },
        { pattern: /^\w{2,10}$/, message: '请输入2~10位的用户名' }
      ]
    }
  },
  methods: {
    async onSubmit (values) {
      try {
        const { data: res } = await loginAPI(values)
        console.log('登录结果', res)
        localStorage.setItem('mobile-token', res.data.token)
        this.$toast('登录成功')
        this.username = this.password = ''
        this.$router.push('/article')
      } catch (error) {
        if (error.response) {
          this.$toast(error.response.data.message)
        } else {
          this.$toast('登录失败')
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.link {
  float:right;
  margin-right: 20px;
  font-size: 14px;
  color: #646566;
}
</style>
